﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DauGiaApp.Models;
using System.Web.Routing;
using System.Web.Script.Serialization;
namespace DauGiaApp.Controllers
{
    public class DauGiaController : Controller
    {
        //
        // GET: /DauGia/
        DauGiaEntities data = new DauGiaEntities();
        #region Binh
        public static JavaScriptSerializer js = new JavaScriptSerializer();
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DangTTDauGia(DauGia dg)
        {
            try
            {
                // check thong tin hop le o day
                dg.SanPham.MaTinhTrangSanPham = 2;
                data.DauGias.AddObject(dg);
                data.SaveChanges();
                return RedirectToAction("ThongBao", "Home", null);
            }
            catch (Exception ex)
            {
                return RedirectToAction("ThongBao", "Home", null);
            }
        }
        public ActionResult DangDauGia(int MaSanPham)
        {
            SanPham spdg = data
                           .SanPhams
                           .Where(sp => sp.MaSanPham == MaSanPham)
                           .Single();
            return View(spdg);
        }

        public ActionResult DSDangDauGia()
        {
            try
            {
                List<DauGia> lsDangDg = data.DauGias
                                        .Where(dg => DateTime.Now.CompareTo(dg.ThoiGianKetThuc) < 0
                                                && dg.SanPham.MaTinhTrangSanPham == 2
                                                )
                                        .ToList();
                return View(lsDangDg);
            }
            catch (Exception ex)
            {
                return View(new List<DauGia>());
            }


        }

        [HttpPost]
        public ActionResult CapNhatBid(int MaDauGia)
        {
            try
            {
                DauGia dg = data.DauGias
                                .Where(tmp => tmp.MaDauGia == MaDauGia)
                                .Single();
                return Json(new
                {
                    KetQua = "ThanhCong",
                    ThongBao = "Bid thất bại",
                    GiaKhopLenh = dg.GiaKhopLenh
                }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new
                {
                    KetQua = "ThatBai",
                    ThongBao = "Không lấy được thông tin bid",
                    GiaKhopLenh = 0
                }, JsonRequestBehavior.AllowGet);
            }

        }

        [HttpPost]
        public ActionResult DatGia(int MaDauGia, decimal GiaTien)
        {
            TaiKhoan tk = (TaiKhoan)Session["user"];
            if (tk == null)
            {
                return Json(new
                        {
                            KetQua = "ThatBai",
                            ThongBao = "DangNhap",
                            MaDauGia = MaDauGia
                        }, JsonRequestBehavior.AllowGet);
            }
            System.Web.HttpContext.Current.Application.Lock();
            // kiem tra user
            // kiem tra ma dau gia

            var kq = Json(new { ID = "01" });
            try
            {
                DauGia dg = data.DauGias
                                .Where(tmp => tmp.MaDauGia == MaDauGia)
                                .Single();
                if (dg != null)
                {
                    if (dg.ThoiGianKetThuc.CompareTo(DateTime.Now) < 0)
                    {
                        throw new Exception("Phiên đấu giá đã kết thúc!");
                    }

                    if (GiaTien > dg.GiaKhopLenh)
                    {

                        dg.SanPham.GiaHienTai = GiaTien;
                        DateTime dt = DateTime.Now;
                        dt = dt.AddMinutes(1);
                        dg.ThoiGianKetThuc = dt;
                        dg.GiaKhopLenh = GiaTien;

                        ChiTietDauGia ctdg = new ChiTietDauGia();
                        ctdg.MaDauGia = dg.MaDauGia;
                        ctdg.ThoiGianGiaoDich = DateTime.Now;
                        ctdg.MaTaiKhoan = tk.MaTaiKhoan;
                        ctdg.GiaGiaoDich = GiaTien;
                        data.ChiTietDauGias.AddObject(ctdg);
                        data.SaveChanges();
                        kq = Json(new
                        {
                            KetQua = "ThanhCong",
                            ThongBao = "Bid thành công",
                            MaDauGia = MaDauGia
                        }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        kq = Json(new
                        {
                            KetQua = "ThatBai",
                            ThongBao = "Giá Bid nhỏ hơn giá khớp lệnh",
                            MaDauGia = MaDauGia
                        }, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    throw new Exception("Khong ton tai ma dau gia nay!");
                }

            }
            catch (Exception ex)
            {
                kq = Json(new
                {
                    KetQua = "ThatBai",
                    ThongBao = ex.Message,
                    MaDauGia = MaDauGia
                },
                                JsonRequestBehavior.AllowGet);
            }
            finally
            {
                System.Web.HttpContext.Current.Application.UnLock();

            }

            return kq;
        }

        [HttpPost]
        public ActionResult GetCountDown()
        {
            try
            {
                List<DauGia> lsDangDg = data.DauGias
                                        .Where(dg => dg.SanPham.MaTinhTrangSanPham == 2)
                                        .ToList();
                var query = from dg in lsDangDg
                            select new
                            {
                                MaDauGia = dg.MaDauGia,
                                GiaKhopLenh = dg.GiaKhopLenh,
                                TaiKhoanCuoi = dg.LayTKDGCuoi().TenTaiKhoan,
                                ThoiGianKetThuc = new
                                {
                                    Nam = dg.ThoiGianKetThuc.Year,
                                    Thang = dg.ThoiGianKetThuc.Month,
                                    Ngay = dg.ThoiGianKetThuc.Day,
                                    Gio = dg.ThoiGianKetThuc.Hour,
                                    Phut = dg.ThoiGianKetThuc.Minute,
                                    Giay = dg.ThoiGianKetThuc.Second
                                }
                            };
                string rtnString = js.Serialize(query);

                return Content(rtnString);
            }
            catch (Exception ex)
            {
                return Content("null");
            }

        }
        #endregion
        #region Bao
        public ActionResult DauGiaThanhCong()
        {
            TaiKhoan currentUser = (TaiKhoan)Session["user"];
            List<DauGia> dsdaugia = (from dg in data.DauGias
                                     where (dg.MaTaiKhoan_ThanhCong == currentUser.MaTaiKhoan)
                                     select dg).ToList();
            return View(dsdaugia);
        }
        public ActionResult DanhGia(int id)
        {
            TaiKhoan currentUser = (TaiKhoan)Session["user"];
            if (currentUser != null)
            {
                DauGia daugia = (from dg in data.DauGias
                                 where (dg.MaDauGia == id)
                                 select dg).Single();
                return View(daugia);
            }
            else
                return View();

        }
        [HttpPost]
        public ActionResult DangDanhGia(string noidung, int id)
        {
            // kiểm tra
            // Lấy cái đấu giá kia ra
            DauGia daugia = (from dg in data.DauGias
                             where (dg.MaDauGia == id)
                             select dg).Single();
            daugia.DanhGia = noidung;
            data.SaveChanges();
            return RedirectToAction("DanhGia", new { id = id });
        }


        public ActionResult XacNhan(int id)
        {
            DauGia daugia = (from dg in data.DauGias
                             where (dg.MaDauGia == id)
                             select dg).Single();
            daugia.SanPham.TaiKhoan.DiemTinCayBan += 5;
            daugia.TaiKhoan.DiemTinCayMua += 3;
            daugia.XacNhan = true;
            data.SaveChanges();
            return RedirectToAction("DauGiaThanhCong");
        }
        #endregion
    }

}
